// ============================================================================
// 响应式设计 Hook
// ============================================================================

import { useState, useEffect } from 'react'

/**
 * 断点定义
 */
export const breakpoints = {
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
  '2xl': 1536
} as const

export type Breakpoint = keyof typeof breakpoints

/**
 * 响应式Hook
 * 提供当前屏幕尺寸和断点检测
 */
export function useResponsive() {
  const [windowSize, setWindowSize] = useState({
    width: typeof window !== 'undefined' ? window.innerWidth : 1024,
    height: typeof window !== 'undefined' ? window.innerHeight : 768
  })

  useEffect(() => {
    if (typeof window === 'undefined') return

    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      })
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  // 检查是否匹配指定断点
  const isAbove = (breakpoint: Breakpoint): boolean => {
    return windowSize.width >= breakpoints[breakpoint]
  }

  const isBelow = (breakpoint: Breakpoint): boolean => {
    return windowSize.width < breakpoints[breakpoint]
  }

  const isBetween = (min: Breakpoint, max: Breakpoint): boolean => {
    return windowSize.width >= breakpoints[min] && windowSize.width < breakpoints[max]
  }

  // 便捷的断点检查
  const isMobile = windowSize.width < breakpoints.md
  const isTablet = windowSize.width >= breakpoints.md && windowSize.width < breakpoints.lg
  const isDesktop = windowSize.width >= breakpoints.lg

  return {
    windowSize,
    isAbove,
    isBelow,
    isBetween,
    isMobile,
    isTablet,
    isDesktop,
    // 具体断点检查
    isSm: isAbove('sm'),
    isMd: isAbove('md'),
    isLg: isAbove('lg'),
    isXl: isAbove('xl'),
    is2Xl: isAbove('2xl')
  }
}

/**
 * 媒体查询Hook
 */
export function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState(false)

  useEffect(() => {
    if (typeof window === 'undefined') return

    const mediaQuery = window.matchMedia(query)
    setMatches(mediaQuery.matches)

    const handleChange = (event: MediaQueryListEvent) => {
      setMatches(event.matches)
    }

    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [query])

  return matches
}

/**
 * 方向检测Hook
 */
export function useOrientation() {
  const { windowSize } = useResponsive()
  
  return {
    isPortrait: windowSize.height > windowSize.width,
    isLandscape: windowSize.width > windowSize.height,
    aspectRatio: windowSize.width / windowSize.height
  }
}

/**
 * 触摸设备检测Hook
 */
export function useTouchDevice(): boolean {
  const [isTouchDevice, setIsTouchDevice] = useState(false)

  useEffect(() => {
    if (typeof window === 'undefined') return

    const checkTouchDevice = () => {
      return (
        'ontouchstart' in window ||
        navigator.maxTouchPoints > 0 ||
        // @ts-ignore
        navigator.msMaxTouchPoints > 0
      )
    }

    setIsTouchDevice(checkTouchDevice())
  }, [])

  return isTouchDevice
}

/**
 * 响应式值Hook
 * 根据断点返回不同的值
 */
export function useResponsiveValue<T>(values: {
  base: T
  sm?: T
  md?: T
  lg?: T
  xl?: T
  '2xl'?: T
}): T {
  const { windowSize } = useResponsive()

  // 从大到小检查断点
  if (values['2xl'] !== undefined && windowSize.width >= breakpoints['2xl']) {
    return values['2xl']
  }
  if (values.xl !== undefined && windowSize.width >= breakpoints.xl) {
    return values.xl
  }
  if (values.lg !== undefined && windowSize.width >= breakpoints.lg) {
    return values.lg
  }
  if (values.md !== undefined && windowSize.width >= breakpoints.md) {
    return values.md
  }
  if (values.sm !== undefined && windowSize.width >= breakpoints.sm) {
    return values.sm
  }

  return values.base
}

/**
 * 网格列数Hook
 * 根据屏幕尺寸返回合适的网格列数
 */
export function useGridColumns(options: {
  sm?: number
  md?: number
  lg?: number
  xl?: number
  '2xl'?: number
} = {}): number {
  const defaultColumns = {
    base: 1,
    sm: options.sm || 2,
    md: options.md || 3,
    lg: options.lg || 4,
    xl: options.xl || 5,
    '2xl': options['2xl'] || 6
  }

  return useResponsiveValue(defaultColumns)
}

/**
 * 容器最大宽度Hook
 */
export function useContainerMaxWidth(): string {
  return useResponsiveValue({
    base: '100%',
    sm: '640px',
    md: '768px',
    lg: '1024px',
    xl: '1280px',
    '2xl': '1536px'
  })
}

/**
 * 侧边栏状态Hook（响应式）
 */
export function useResponsiveSidebar() {
  const { isMobile } = useResponsive()
  
  // 移动端默认折叠，桌面端默认展开
  const getDefaultCollapsed = () => isMobile
  
  return {
    shouldAutoCollapse: isMobile,
    getDefaultCollapsed
  }
}
